package sorter;

import java.rmi.AccessException;
import java.rmi.NotBoundException;
import java.rmi.RemoteException;
import java.rmi.registry.LocateRegistry;
import java.rmi.registry.Registry;
import java.util.Observable;

public class SorterThread extends Observable implements Runnable{

	private Thread mythread;
	private boolean running;
	Comparable[] myList;
	Comparable[] result;
	private int myThreadNumber;
	
	public SorterThread(Comparable[] list, ListJoiner myListJoiner){
		
	      
	      running = true;
	      myList = list;	      
	      myThreadNumber = myListJoiner.getNextThreadNumber();
	      addObserver(myListJoiner);
	            
	}
	

	public int getThreadNumber(){		
		return myThreadNumber;
	}
	
	public Comparable[] sort(Comparable[] list) throws AccessException, RemoteException, NotBoundException{
		Registry registry = LocateRegistry.getRegistry(1100);
		ISortFactory myISortFactory = (ISortFactory) registry
				.lookup("mysortfactory");
		ISorter sorter = myISortFactory.createSorter();
		result = sorter.sort(list);
		return result;		
	}
	
	@Override
	public void run() {
		Thread thisThread = Thread.currentThread();
	      while ( running )
	      { 	        
				try {
					sort(myList);

				} catch (AccessException e) {
					e.printStackTrace();
				} catch (RemoteException e) {
					e.printStackTrace();
				} catch (NotBoundException e) {
					e.printStackTrace();
				}	
				setChanged();
				notifyObservers(result);
				clearChanged();
				stop();
	      }		
	}
	
	public void stop()
	   {  
		running = false;
	   } 

}
